package mysql

import (
	"errors"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/models"
	mysqlClients "gitee.com/captials-team/ubdframe/src/infrastructure/clients/mysql"
	"gorm.io/gorm"
	"strings"
)

func NewMetricLatestDataDao(conf configstc.DBConfig) *MetricLatestDataDao {
	return &MetricLatestDataDao{
		db:   mysqlClients.NewGormDB(conf),
		conf: conf,
	}
}

type MetricLatestDataDao struct {
	db   *gorm.DB
	conf configstc.DBConfig
	GormDaoHelp
	metricDaoHelp
}

func (dao *MetricLatestDataDao) Query(metricId int64) (*models.MetricData, error) {
	if metricId == 0 {
		return nil, fmt.Errorf("param err")
	}
	var info models.MetricData
	db := dao.db.Model(&info)
	db = db.Table(new(models.MetricLatestData).TableName(dao.db.NamingStrategy))
	ret := db.First(&info, "metric_id = ?", metricId)
	if errors.Is(ret.Error, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	if ret.Error != nil {
		return nil, ret.Error
	}
	return &info, nil
}

func (dao *MetricLatestDataDao) Add(add *models.MetricData) (int64, error) {
	ret := dao.db.Model(add).Create(add)
	if ret.Error != nil {
		return 0, ret.Error
	}
	if ret.RowsAffected == 0 {
		return 0, fmt.Errorf("add fail")
	}

	return add.Id, nil
}

func (dao *MetricLatestDataDao) BatchAdd(adds ...*models.MetricData) (int64, error) {
	var sql []string
	for _, v := range adds {
		sql = append(sql, dao.SQLForWriteMetricData(new(models.MetricLatestData).TableName(dao.db.NamingStrategy), []models.MetricData{*v}))
	}

	ret := dao.db.Exec(strings.Join(sql, ";"))
	return ret.RowsAffected, ret.Error
}

func (dao *MetricLatestDataDao) Migrate() (int64, error) {
	return 1, dao.db.AutoMigrate(new(models.MetricLatestData))
}

func (dao *MetricLatestDataDao) DB() *gorm.DB {
	return dao.db
}

func (dao *MetricLatestDataDao) Use(db *gorm.DB) interfaces.ItfMetricLatestDataDao {
	return &MetricLatestDataDao{db: db}
} //使用db
